package com.blm.util;

import com.blm.common.constants.ExceptionConstant;
import com.blm.entity.User;
import com.blm.exception.CommonException;
import com.blm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class SecurityUtil {

    @Autowired
    private UserService userService;

    public Long getCurrentUserId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            throw new CommonException(ExceptionConstant.REQ_UNAUTHORIZED);
        }
        String username = auth.getName();
        User user = userService.findUserByUsername(username);
        return user.getId();
    }
}